<?php
namespace app\tadmin\controller;
use app\tadmin\model\Category as CategoryModel;
use app\tadmin\model\Type as TypeModel;
/**
 * 文档分类
 * Class Index
 * @package app\tadmin\controller
 */
class Category extends Controller
{
    public function index()
    {
        $types = TypeModel::kv();
        $cateTree = CategoryModel::getTree($types);
        return $this->fetch('index' , compact('cateTree'));
    }

    public function tree($tree = null , $level = 0){
        echo $this->fetch('tree' , compact('tree', 'level'))->getContent();
    }

    /**
     * 跳转至模型列表页
     */
    public function doc()
    {
        $category_id = input('category_id');
        $cate = CategoryModel::get($category_id);
        $type = TypeModel::get($cate['type']);
        $this->redirect('category.'.$type['model_table'].'/index' , ['category_id'=>$category_id]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            $parent_id = input('parent_id' , 0);
            $parent_text = "顶级栏目";
            if($parent_id > 0){
                $parent = CategoryModel::where('id' , $parent_id)->find();
                $parent_text = $parent->title;
            }
            $types = TypeModel::all();
            return $this->fetch('add', compact('types', 'parent_id' , 'parent_text'));
        }
        $model = new CategoryModel;
        if ($model->add($this->postData('category'))) {
            return $this->renderSuccess('添加成功', url('category/index'));
        }
        $error = $model->getError() ?: '添加失败';
        return $this->renderError($error);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        if (!$this->request->isAjax()) {
            $types = TypeModel::all();
            $parent_id   = 0;
            $parent_text = "顶级栏目";
            $category = CategoryModel::get(input('category_id'));
            if($category['parent_id'] > 0){
                $parent = CategoryModel::where('id' , $category['parent_id'])->find();
                $parent_text = $parent->title;
            }
            return $this->fetch('edit', compact('types', 'parent_id' , 'parent_text' , 'category'));
        }
        $data = $this->postData('category');
        $model = CategoryModel::get($data['id']);
        unset($data['id']);
        if ($model->edit($data)) {
            return $this->renderSuccess('编辑成功', url('category/index'));
        }
        $error = $model->getError() ?: '编辑失败';
        return $this->renderError($error);
    }

    public function delete($category_id)
    {
        $model = CategoryModel::get($category_id);
        if (!$model->remove()) {
            return $this->renderError('删除失败,错误:'.$model->error);
        }
        return $this->renderSuccess('删除成功');
    }

}
